package tr.muyat.accelerometer.visualizer;

import info.monitorenter.gui.chart.Chart2D;
import info.monitorenter.gui.chart.ITrace2D;
import info.monitorenter.gui.chart.traces.Trace2DLtd;

import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

/**
 * 
 * 
 * @author fxulusoy
 */
public class Chart implements Runnable {

	private JFrame frame;
	private ITrace2D xTrace;
	private ITrace2D yTrace;
	private ITrace2D zTrace;
	/** The start time of this collector. */
	private long startTime;
	
	/**
	 * Constructor.
	 */
	public Chart() {
		startTime = System.currentTimeMillis();
	}

	@Override
	public void run() {

		// Create a chart:
		Chart2D chart = new Chart2D();
		// Create an ITrace:
		// Note that dynamic charts need limited amount of values!!!
		xTrace = new Trace2DLtd(200, "X-value");
		xTrace.setColor(Color.RED);
		yTrace = new Trace2DLtd(200, "Y-value");
		yTrace.setColor(Color.BLUE);
		zTrace = new Trace2DLtd(200, "Z-value");
		zTrace.setColor(Color.GREEN);

		// Add the trace to the chart. This has to be done before adding points
		// (deadlock prevention):
		chart.addTrace(xTrace);
		chart.addTrace(yTrace);
		chart.addTrace(zTrace);

		// Make it visible:
		// Create a frame.
		frame = new JFrame("MinimalDynamicChart");
		// add the chart to the frame:
		frame.getContentPane().add(chart);
		frame.setSize(400, 300);
		// Enable the termination button [cross on the upper right edge]:
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				// System.exit(0);
			}
		});
		frame.setVisible(true);
		
	}
	
	public void remove() {
		frame.setVisible(true);
		frame.dispose();
	}
	
	public void addPoint(double x, double y, double z) {
		
		synchronized (this) {
			double timestamp = ((double) System.currentTimeMillis() - this.startTime);
			xTrace.addPoint(timestamp, x);
			yTrace.addPoint(timestamp, y);
			zTrace.addPoint(timestamp, z);
		}
		
	}

}

